/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.hutech09.jsale.web.manager.users;

import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.hutech09.jsale.bsn.IAccessUserManager;
import org.hutech09.jsale.bsn.exception.ItemNotFoundException;
import org.hutech09.jsale.entity.AccessUser;

/**
 *
 * @author Nam
 */
@ManagedBean
@SessionScoped
public class LoggedInUser  implements Serializable{

    private AccessUser currentUser;

    @EJB
    private IAccessUserManager userManager;

    @EJB
    private IAccessUserManager aum;

    /**
     * Creates a new instance of LoggedInUser
     */
    public LoggedInUser() {
    }

    public AccessUser getCurrentUser() {
        if (currentUser == null) {
            String userId;
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
            userId = request.getUserPrincipal().getName();
            this.currentUser = userManager.findById(userId);
            System.out.println(userId);

        }
        return currentUser;
    }

    public void setCurrentUser(AccessUser currentUser) {
        this.currentUser = currentUser;
    }

    public void update() {
        try {
            aum.update(currentUser);
        } catch (ItemNotFoundException ex) {
            Logger.getLogger(LoggedInUser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
